import React, {Component, Fragment} from 'react';
import TodoItem from './TodoItem';

// 定义一个React组件
class TodoList extends Component {
  
  // 组件刚被创建的时候，constructor会被自动执行
  constructor(props){
    super(props);
    this.state = {
      title: 'My To-do List',
      list: [
        'learn React',
        'write Blog'
      ],
      doneList: [],
      inputValue: ''
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.addList = this.addList.bind(this);
    this.handleTodoItem = this.handleTodoItem.bind(this);
    this.handleDeleteTodo = this.handleDeleteTodo.bind(this);
    this.handleDeleteDone = this.handleDeleteDone.bind(this);
  }

  handleInputChange(e){
    this.setState({
      inputValue: e.target.value
    })
  }
  
  addList() {
    // 添加to-do事件
    this.setState({
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
    })
    // console.log('add List')
  }

  handleTodoItem(index){
    // 处理todo事件，将事件从list移动到doneList中
    let item = this.state.list[index];
    const todoList = [...this.state.list];
    todoList.splice(index, 1);
    this.setState({
      list: todoList,
      doneList: [...this.state.doneList,item]
    })
  }

  handleDeleteTodo(index){
    // 供子组件调用,删除todo事件项
    const newList = [...this.state.list];
    newList.splice(index, 1);
    this.setState({
      list: newList
    })
  }

  handleDeleteDone(index){
    // 删除done事件项
    const newList = [...this.state.doneList];
    newList.splice(index, 1);
    this.setState({
      doneList: newList
    })
  }

  getTodoItems(){
    return (
      this.state.list.map((item,index) => {
        return (
          <TodoItem
            delete={this.handleDeleteTodo}
            handle={this.handleTodoItem}
            key={index}
            content={item}
            index={index} />
        )
      })
    )
  }

  getDoneItems(){
    return (
      this.state.doneList.map((item,index) => {
        return (
          <TodoItem
            delete={this.handleDeleteDone}
            key={index}
            content={item}
            index={index} />
        )
      })
    )
  }

  render() {
    return (
    <Fragment>
      <h3 className="title">{this.state.title}</h3>
      <div className="header">
        <input
          value={this.state.inputValue} 
          onChange={this.handleInputChange} />
        <button
          className="add-btn"
          onClick={this.addList}>
          add
        </button>
      </div>
      <ul>{this.getTodoItems()}</ul>
      <hr />
      <ul>{this.getDoneItems()}</ul>
      <div className="remarks">You can click item if you have done it!</div>
    </Fragment>
  );
  }
}

// 定义完之后要导出，这样其他才可以import
export default TodoList;
